<?php
/**
 * Created by PhpStorm.
 * User: yui
 * Date: 2017/4/8
 * Time: 23:22
 */

namespace common\services;

use Yii;
use common\models\UserLogin;

class UserSve extends BaseSve
{
    public function login(array $post):array
    {
        try {
            $UserLogin = new UserLogin();
            $UserLogin->load($post);
            //验证
            self::checkErr($UserLogin);
            $rs = $UserLogin->login();
            if ($rs === true) {
                return self::result('登录成功', 0);
            } else {
                return self::result('登录失败');
            }
        } catch (\Exception $e) {
            if (array_key_exists($e->getCode(), OC_ERR_CODE)) {
                return self::result($e->getMessage(), $e->getCode());
            } else {
                return self::result('系统繁忙', -50);
            }
        }
    }

    /**
     * 退出登录
     * @return array
     */
    public function logout():array
    {
        try {
            $token = Yii::$app->user->identity->token;
            if (!empty($token)) {
                Yii::$app->cache->delete($token);
            }
            if (Yii::$app->user->logout()) {
                return self::result('退出成功', 0);
            }
            return self::result('退出失败');
        } catch (\Exception $e) {
            if (array_key_exists($e->getCode(), OC_ERR_CODE)) {
                return self::result($e->getMessage(), $e->getCode());
            } else {
                return self::result('系统繁忙', -50);
            }
        }
    }
}